package com.WhosOn;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class WhosOn extends Activity {
	
	public void comprobar() throws IOException {
        int c;
        Socket s = null;
        InputStream sIn = null;
        OutputStream sout;
        String str="";
        try {
            s = new Socket( "iv.no-ip.info",4321 );
        } catch( IOException e ) {
            System.out.println( e );
        }
        //enviar nombre
        sout = s.getOutputStream();
        final EditText edt = (EditText) findViewById(R.id.edt);
        String nombre;
        nombre = edt.getText().toString();
        if(nombre.equals("")) Toast.makeText(this, "Pon algo en el nombre", 3).show();
        else {
	        for( int i=0; i < nombre.length(); i++ )
	            sout.write( (int)nombre.charAt( i ) );
	        System.out.println("Nombre enviado");
	        s.shutdownOutput();
	        //recibir lista
			sIn = s.getInputStream();
	        while( ( c = sIn.read() ) != -1 )
	            str = str + (char)c;
	    	final TextView txt = (TextView) findViewById(R.id.txt);
	    	final ListView lst = (ListView) findViewById(R.id.lst);
	    	if(str.indexOf(";") != -1) {
		    	String lista[] = str.split(";");
		    	txt.setText("Conectado al servidor " + lista[0] + ":");
		    	str = str.substring(lista[0].length() + 1);
		    	lista = str.split(";");
		    	lst.setAdapter(new ArrayAdapter<String>(this, R.layout.lista, lista));
	    	}
	    	else {
	    		txt.setText("Conectado al servidor " + str + ":");
	    		String lista[] = {};
	    		lst.setAdapter(new ArrayAdapter<String>(this, R.layout.lista, lista));
	    	}
        }
        s.close();
	}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final Button button = (Button) findViewById(R.id.btn);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                try {
					comprobar();
				} catch (IOException e) {
				}
            }
        });
    }
}